package com.bibi.zoo.service;

import com.bibi.zoo.pkg.resp.BaseResp;
import com.bibi.zoo.pkg.resp.RespCheckGame;
import com.bibi.zoo.web.req.ReqBuy;
import com.bibi.zoo.web.req.ReqInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class TuziTaskService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private HandleService handleService;
    ExecutorService pool = Executors.newCachedThreadPool();
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private AccountService accountService;
    /**
     * 动物id
     */
    int aid = 3;

    /*private String phone = "17557283167";
    private String pwd = "Zard1998";*/

    @Scheduled(cron = "0 18 14 * * ?")
//    @Scheduled(cron = "0/3 * * * * ?")
    public void loginTask() {
        logger.info("开启登录任务");
        List<ReqInput> tuzi = accountService.getTuzi();
        for(int i=0; i<tuzi.size();i++) {
            ReqInput reqInput = tuzi.get(i);
            Constants.luckkeyMap.removeAll(reqInput.getPhone());
            ReqInput req = new ReqInput();
            req.setPhone(reqInput.getPhone());
            req.setPwd(reqInput.getPwd());
            while (Constants.luckkeyMap.get(reqInput.getPhone()).size() < 10) {
                handleService.getLuckkey(req);
            }
        }

        Set<String> phones = Constants.luckkeyMap.keySet();
        for(String phone : phones) {
            HttpHeaders authHeaders = new HttpHeaders();
            authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
            authHeaders.add("luckkey",Constants.luckkeyMap.get(phone).get(0));
            authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            ReqBuy req = new ReqBuy();
            req.setZid(aid);
            req.setPhone(phone);
            handleService.invite(authHeaders,req);
        }

    }

    @Scheduled(cron = "0 25 14 * * ?")
    public void buyTask() throws InterruptedException {
        logger.info("开启抢购任务");
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Set<String> phones = Constants.luckkeyMap.keySet();
        String phoneBase = null;
        int i=0;
        for(String phone : phones) {
            if(i++ == 0) {
                phoneBase = phone;
            }
            asynBuy(countDownLatch,phone);
        }
        RespCheckGame respCheckGame = null;
        while (respCheckGame == null) {
            respCheckGame = handleService.checkGame(phoneBase);
        }
        long time = respCheckGame.getData().getTime();
        if(time > 0) {
            Thread.sleep(time * 1000);
//            Thread.sleep(5000);
        }
        countDownLatch.countDown();
    }
    private void asynBuy(CountDownLatch countDownLatch,String phone) {
        List<String> keys = Constants.luckkeyMap.get(phone);
        long shold = 500;
        for(int i=0;i<keys.size();i++) {
            String luckkey = keys.get(i);
            pool.execute(() -> {
                HttpHeaders authHeaders = new HttpHeaders();
                authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
                authHeaders.add("luckkey",luckkey);
                authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
                Map<String,Object> params = new HashMap<>();
                params.put("id", aid);
                try {
                    logger.info("{}进入抢购阻塞{}",phone,luckkey);
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int j=0;j<30;j++) {
                    long start = System.currentTimeMillis();
                    try{
                        BaseResp baseResp = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/game/flash_buy/{id}", requestEntity2, BaseResp.class,params);
                        logger.info("phone:{},抢购结果：{}", phone,com.alibaba.fastjson.JSONObject.toJSONString(baseResp));
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                    long end = System.currentTimeMillis();
                    long wait = shold-(end - start);
                    if(wait > 0) {
                        try {
                            if(wait > 50) {
                                wait = wait + new Random().nextInt(100) - 50;
                            }
                            Thread.sleep(wait);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            Thread.sleep(new Random().nextInt(50));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        pool.execute(() -> {
            HttpHeaders authHeaders = new HttpHeaders();
            authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
            authHeaders.add("luckkey",keys.get(0));
            authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
            Map<String,Object> params = new HashMap<>();
            params.put("id", aid);
            try {
                countDownLatch.await();
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int j=0; j<100; j++) {
                long start = System.currentTimeMillis();
                try {
                    ResponseEntity<BaseResp> exchange = restTemplate.exchange("http://luck9.luckyzodiac12.com/api/game/checkOpen/{id}", HttpMethod.GET, requestEntity2, BaseResp.class, params);
                    logger.info("phone:{},开奖结果:{}",phone,com.alibaba.fastjson.JSONObject.toJSONString(exchange.getBody()));
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                long end = System.currentTimeMillis();
                long wait = 2000 - (end - start);
                if(wait > 0) {
                    try {
                        Thread.sleep(wait);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
